﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using CentaLine.Infrastructure;
using CentaLine.Repository;

namespace CentaLine.WinService
{
    public partial class Service : ServiceBase
    {
        public Service()
        {
            try
            {
                InitializeComponent();
                Thread th = new Thread(DoWork);
                th.Start();
            }
            catch (Exception e)
            {

                Logger.LogDB.Error("服务运行异常->", e);
            }
        }

        protected override void OnStart(string[] args)
        {
            Logger.LogDB.Info("服务启动");
        }

        protected override void OnStop()
        {
            Logger.LogDB.Info("服务停止");
        }

        public void DoWork()
        {
            int hour = Convert.ToInt16(ConfigurationManager.AppSettings["ServiceStartTime"]);//服务开始运行时间
            while (true)
            {
                if (DateTime.Now.Hour == hour)
                {
                    var vp = new VitualPhoneManager();
                    var res = vp.AutoAssign();
                    if (res.Result)
                    {
                        Logger.LogDB.Info("服务运行成功->" + res.Message);
                    }
                    else
                    {
                        Logger.LogDB.Error("服务运行失败->" + res.Exception);
                    }
                    double interval = (DateTime.Now.Date.AddDays(1) - DateTime.Now).TotalMilliseconds;
                    Logger.Log.Info("睡眠时间:" + (interval - 1200000));
                    Thread.Sleep(Convert.ToInt32(interval - 1200000)); //第二日0点运行 600000->10分钟用于时间缓冲 
                }
            }
        }
    }
}
